﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EasyClassServer.Net;

namespace EasyClassServer.Application.Register
{
    class Register : IApplication
    {
        public string Name => "register";

        public HttpResponseArgs Handle(HttpArgs args)
        {
            RegisterModel model = new RegisterModel();
            var email = (string)args.GetPostValue()["email"];
            var pwd = (string)args.GetPostValue()["pwd"];
            var verificationcode = args.GetPostValue()["verificationcode"].ToString();
            var type = (string)args.GetPostValue()["type"];
            var name = (string)args.GetPostValue()["name"];
            var emailindex = args.GetPostValue()["emailindex"].ToString();
            if (model.Find("email", email))
            {
                Data.CacheManager.RemoveCache("mail" + emailindex);
                return new HttpResponseArgs()
                {
                    Code = HttpCode.Error,
                    Message = "邮箱已被注册",
                    Data = new RegisterModel
                    {
                        Error = RegisterModel.ErrorType.AlreadyExists
                    }
                };
            }
            object correct_validate = Data.CacheManager.GetCache("mail" + emailindex);
            if (correct_validate == null || correct_validate.ToString() != verificationcode)
            {
                return new HttpResponseArgs()
                {
                    Code = HttpCode.Error,
                    Message = "验证码错误",
                    Data = new RegisterModel
                    {
                        Error = RegisterModel.ErrorType.WorngCode
                    }
                };
            }
            try
            {
                model.Insert(new Dictionary<string, object>
                {
                    { "email", email },
                    { "name", name },
                    { "pwd", pwd },
                    { "type", type }
                });
                Data.CacheManager.RemoveCache("mail" + emailindex);
            }
            catch(Exception e)
            {
                return new HttpResponseArgs()
                {
                    Code = HttpCode.Error,
                    Message = e.Message,
                    Data = null
                };
            }
            return new HttpResponseArgs()
            {
                Code = HttpCode.Sucsess,
                Message = "注册成功",
                Data = new RegisterModel
                {
                    Error = RegisterModel.ErrorType.Success
                }
            };
        }
    }
}
